package cn.sptpc.utils;

import cn.hutool.core.util.IdUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


public class FileUtils {
    private static String filename;

    public static InputStream uploadFile(HttpServletRequest request){
        InputStream in = null;
        try{
            // 2. 使用Apache文件上传组件处理文件上传
            // 2.1 创建一个DiskFileItemFactory工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 2.2 创建一个文件上传解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 解决上传文件名的中文乱码
            upload.setHeaderEncoding("UTF-8");
            // 2.3 判断提交上来的数据是否是上传表单的数据
            if(!ServletFileUpload.isMultipartContent(request)){
                return null;
            }
            // 2.4 使用ServletFileUpload解析器解析上传数据
            List<FileItem> list = upload.parseRequest(request);
            for(FileItem item : list){
                // 如果fileitem中封装的是上传文件
                if(!item.isFormField()) {
                    String savedFileName = "";
                    // 得到上传的文件名称
                    filename = item.getName();

                    if(filename==null || filename.trim().equals("")){
                        continue;
                    }
                    // 注意：不同的浏览器提交的文件名是不一样的，有些浏览器提交上来的文件名是带有路径的，如：  c:\a\b\1.txt，而有些只是单纯的文件名，如：1.txt
                    // 处理获取到的上传文件的文件名的路径部分，只保留文件名部分
                    filename = filename.substring(filename.lastIndexOf("/")+1);
                    filename = IdUtil.randomUUID()+ filename.substring(filename.lastIndexOf("."));
                    // 获取item中的上传文件的输入流
                    in = item.getInputStream();
                }
                // 删除处理文件上传时生成的临时文件
                item.delete();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return in;
    }
    //下载文件
    public static boolean downloadFile(String path,String filename,OutputStream out){
        File file=new File(path+"/"+filename);
        FileInputStream in= null;
        try {
            in = new FileInputStream(file);

            byte[] b=new byte[1024];
            int temp=0;
            while((temp=in.read(b))!=-1){
                out.write(b, 0, temp);
            }
            out.flush();
            out.close();
            in.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    //保存源文件
    public static String saveNative(InputStream in,String savePath){
        File file = new File(savePath);
        //判断保存路径是否存在
        if (!file.exists() && !file.isDirectory()) {
            //创建目录
            file.mkdir();
        }
        try {
            FileOutputStream out = new FileOutputStream(savePath + "/" + filename);
            byte buffer[] = new byte[1024];
            int len = 0;
            while((len=in.read(buffer))>0){
                out.write(buffer, 0, len);
            }
            // 关闭输出流
            out.close();
            System.out.println(filename);
            return filename;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    };
    //保存压缩图片
    public static String saveCompressPic(InputStream in,String savePath){
        if (!filename.substring(filename.lastIndexOf(".")+1).equals("jpg")){
            filename = filename.substring(0,filename.lastIndexOf(".")+1)+"jpg";
        }
        File file = new File(savePath);
        //判断保存路径是否存在
        if (!file.exists() && !file.isDirectory()) {
            //创建目录
            file.mkdir();
        }
        try {
            FileOutputStream out = new FileOutputStream(savePath + "/" + filename);
            compressPicForScale(in,out);
            byte buffer[] = new byte[1024];
            int len = 0;
            while((len=in.read(buffer))>0){
                out.write(buffer, 0, len);
            }
            // 关闭输入流
            in.close();
            // 关闭输出流
            out.close();
            return filename;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    };
    //WordToImg
    public static String saveWordToImg(InputStream in,String savePath){
        if (!filename.substring(filename.lastIndexOf(".")+1).equals("jpg")){
            filename = filename.substring(0,filename.lastIndexOf(".")+1)+"jpg";
        }
        File file = new File(savePath);
        //判断保存路径是否存在
        if (!file.exists() && !file.isDirectory()) {
            //创建目录
            file.mkdir();
        }
        try {
            FileOutputStream out = new FileOutputStream(savePath + "/" + filename);
            Word2Img.wordToImg(in,out);
            byte buffer[] = new byte[1024];
            int len = 0;
            while((len=in.read(buffer))>0){
                out.write(buffer, 0, len);
            }
            // 关闭输入流
            in.close();
            // 关闭输出流
            out.close();
            return filename;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //图片压缩
    private static OutputStream compressPicForScale(InputStream is,OutputStream os) {
        try {
            if (is == null || is.available() <= 0 || is.available() < 500 * 1024) {
                return os;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        try {
            long srcSize = is.available();
            double accuracy = getAccuracy(srcSize / 1024);
            System.out.println(srcSize);
            while (is.available() > 500 * 1024) {

                Thumbnails.of(is)
                        .scale(accuracy)
                        .outputQuality(accuracy)
                        .toOutputStream(os);
            }

        } catch (Exception e) {

        }
        return os;
    }
    //控制图片大小
    private static double getAccuracy(long size) {
        double accuracy;
        if (size < 900) {
            accuracy = 0.85;
        } else if (size < 2047) {
            accuracy = 0.6;
        } else if (size < 3275) {
            accuracy = 0.4;
        } else {
            accuracy = 0.2;
        }
        return accuracy;
    }
}
